from google.appengine.ext import db
from google.appengine.ext import search
from django import newforms as forms
from google.appengine.ext.db import djangoforms

from utils import counter
import search2

"""
This file specifies all the models and their forms that are needed for the help
The hierarchy of help goes as follows

   ROOT
   |--- Topic 1
   |--- Topic 2
       |--- SubTopic 2.1
       |--- SubTopic 2.2
           |--- Question 2.2.1
           |--- Question 2.2.2

"""

class Topic(db.Model):
    "Data Structure for Topic and Subtopic relation"
    name = db.StringProperty(required = True)
    head = db.SelfReferenceProperty('parent', 'child', required=False)
    status = db.BooleanProperty(default = True)
    is_template = db.BooleanProperty(default = False)
    
    created = db.DateTimeProperty(auto_now = True)
    modified = db.DateTimeProperty(auto_now_add = True)

def topic_list(active = True, is_template = False):
    """Every topic has to be a child of ROOT.
    Every subtopic is a child of some topic
    """
    if Topic.all().filter('status = ', active).filter('is_template = ', is_template).count() == 0:
        if Topic.all().count() == 0:
            Topic(name='Root', owner=None,status=True,is_template=True).put()
        q = Topic.all()
    else:
        q = Topic.all().filter('status = ', active).filter('is_template = ', is_template)
    return ((str(c.key()),c.name) for c in q)

class Questions(search2.SearchableModel):
    "Data Structure for Questions and Answers"
    q = db.TextProperty(required = True)
    a = db.TextProperty(required = True)
    
    featured = db.BooleanProperty(default=False)
    head = db.ReferenceProperty(Topic, collection_name = 'child_questions')
    status = db.BooleanProperty(default=True)
    tags = db.StringListProperty()    
    
    created = db.DateTimeProperty(auto_now = True)
    modified = db.DateTimeProperty(auto_now_add = True)

class Picture(db.Model):
    "Used for storing and serving some images dynamically"
    pic = db.BlobProperty()
    
    created = db.DateTimeProperty(auto_now = True)
    modified = db.DateTimeProperty(auto_now_add = True)

class TopicForm(djangoforms.ModelForm):
    "Form for Topic and Subtopic"
    # For the hack, check
    # http://stackoverflow.com/questions/503295/query-distinct-list-of-choices-for-django-form-with-app-engine-datastore
    def __init__(self, *args, **kwargs):
        super(TopicForm, self).__init__(*args, **kwargs)
        choices=[(k,v) for k,v in topic_list(is_template=True)]
        self.fields['head'] = forms.ChoiceField(choices=choices)
    name = forms.CharField(widget=forms.TextInput(attrs={'id':'quest', 'size':40}))

    class Meta:
        model = Topic
        fields = ['name', 'status','head', 'is_template']

class QuestionsForm(djangoforms.ModelForm):
    "Form for questions"
    def __init__(self, *args, **kwargs):
        super(QuestionsForm, self).__init__(*args, **kwargs)
        choices = [(k,v) for k,v in topic_list(is_template=False)]
        self.fields['head'] = forms.ChoiceField(choices=choices)
    q = forms.CharField(widget=forms.TextInput(attrs={
        'id':'quest',
        'size':60,}))
    a = forms.CharField(widget=forms.Textarea(attrs={
      'id':'answ',
      'rows': 20,
      'cols': 70,
      'class': 'tinyMCEditor',}))
    tags = forms.CharField(widget=forms.TextInput(attrs={'label':'Tags','id':'tags', 'size':40}))
    
    class Meta:
        model = Questions
        fields = ['q', 'a', 'head', 'featured', 'status', 'tags']

class Tags(db.Model):
    all_tags = db.StringListProperty()
    
    @classmethod
    def count(cls, tagname):
        """Returns the count of counter with name - tagname"""
        if tagname:
            tagname = 'tag_' + tagname
            return counter.get_count(tagname)
    
    @classmethod
    def increment_count(cls, tagnames):
        """Increment the count for the tagnames present in tagnames"""
        if not isinstance(tagnames, list):
            tag_names = [tagnames]
        else:
            tag_names = tagnames
        for tag_name in tag_names:
            tag_name = 'tag_' + tag_name
            counter.increment(tag_name)

def save_tags(tags):
    "Stores the tags in datastore"
    tag_entity = Tags.all().get()
    if tag_entity is not None:
        existing_tags = tag_entity.all_tags
        if isinstance(tags, list):
            existing_tags.extend(tags)
        else:
            existing_tags.append(tags)
        existing_tags = list(set(existing_tags))
        tag_entity.all_tags = existing_tags
        tag_entity.put()
    else:
        Tags(all_tags = list(tags)).put()